<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once ('./application/controllers/authenticate.php');

class Article extends Authenticate {

    const ARTICLE_PER_PAGE = 15;
    const ARTICLE_PAGE_RANGE = 5;

    public $_rpps = array(10, 15, 20, 25, 30, 45, 100, 200);

    public $_bas = array(
        'Xóa' => 'admin/cms/article/bulk_action/delete',
        'Xuất bản' => 'admin/cms/article/bulk_action/publish',
        'Gỡ bỏ' => 'admin/cms/article/bulk_action/unpublish'
    );

    function __construct() {
        parent::__construct();
        $this->load->model('admin_model');
        $this->load->model('site_role_model');
        $this->load->model('cms_article_model');
        $this->load->model('cms_category_model');
        $this->load->library('upload');
    }

    protected function _eventLoadLayout() {
        $this->page['title'] = 'Quản lý bài viết';
        $this->module['title'] = 'Quản lý bài viết';
    }

    private function check_has_privileges($data = array()) {
        $data['has_privilege_view_article'] = false;
        $data['has_privilege_new_article'] = false;
        $data['has_privilege_edit_article'] = false;
        $data['has_privilege_delete_article'] = false;
        $data['has_privilege_publish_article'] = false;
        $data['has_privilege_unpublish_article'] = false;
        $data['has_privilege_list'] = false;
        $data['is_admin'] = false;
        if ($this->admin_model->is_admin()) {
            $data['has_privilege_view_article'] = true;
            $data['has_privilege_new_article'] = true;
            $data['has_privilege_edit_article'] = true;
            $data['has_privilege_delete_article'] = true;
            $data['has_privilege_publish_article'] = true;
            $data['has_privilege_unpublish_article'] = true;
            $data['has_privilege_list'] = true;
            $data['is_admin'] = true;
        } else {
            $privileges = $this->admin_model->get_privileges();
            if (isset($privileges['admin/cms/article/view'])) {
                $data['has_privilege_view_article'] = true;
            }
            if (isset($privileges['admin/cms/article/new'])) {
                $data['has_privilege_new_article'] = true;
            }
            if (isset($privileges['admin/cms/article/edit'])) {
                $data['has_privilege_edit_article'] = true;
            }
            if (isset($privileges['admin/cms/article/delete'])) {
                $data['has_privilege_delete_article'] = true;
            }
            if (isset($privileges['admin/cms/article/publish'])) {
                $data['has_privilege_publish_article'] = true;
            }
            if (isset($privileges['admin/cms/article/unpublish'])) {
                $data['has_privilege_unpublish_article'] = true;
            }
            if (isset($privileges['admin/cms/article/index'])) {
                $data['has_privilege_list'] = true;
            }
        }
        return $data;
    }

    public function restricted() {
        $this->setPageContent('admin/cms/article/restricted', null);
        $this->renderLayout('layouts/fullcolumn');
    }

    public function index() {
        try {
            $this->filtered_list('index');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    protected function _initListData($return_url, $status, $title, $data = array()) {
        $is_admin = $this->admin_model->is_admin();
        $filters = $this->input->post('filters');
        $current_page = intval($this->input->post('current_page'));
        $record_per_page = intval($this->input->post('record_per_page'));
        if ($record_per_page == 0) {
            $record_per_page = self::ARTICLE_PER_PAGE;
        }
        $conds = null;
        $filters['status']['type'] = 'equal';
        if (!is_integer($status)) {
            $filters['status']['value'] = '';
        } else {
            $filters['status']['value'] = intval($status);
        }
        // Init Filters
        if (!isset($filters['ca.id'])) {
            $filters['ca.id']['value'] = "";
            $filters['ca.id']['type'] = 'equal';
        }
        if (!isset($filters['title'])) {
            $filters['title']['type'] = 'text';
            $filters['title']['value'] = null;
        }

        if ($filters) {
            $conds = analyze_filters($filters);
        }

        if (empty($filters['created_at_from'])) {
            $filters['created_at_from'] = null;
        } else {
            $created_at_from = get_time_stamp($filters['created_at_from']);
            $conds['created_at_from'] = 'ca.created_at >= ' . $created_at_from;
        }
        if (empty($filters['created_at_to'])) {
            $filters['created_at_to'] = null;
        } else {
            $created_at_to = get_time_stamp($filters['created_at_to']);
            if (isset($created_at_from)) {
                if ($created_at_from >= $created_at_to) {
                    $conds['created_at_from'] = 'ca.created_at >= ' . $created_at_to;
                    $filters['created_at_from'] = date('d/m/Y', $created_at_to);
                }
            }
            $conds['created_at_to'] = 'ca.created_at <= ' . get_time_stamp($filters['created_at_to'], true);
        }

        if (empty($filters['publish_day_from'])) {
            $filters['publish_day_from'] = null;
        } else {
            $publish_day_from = get_time_stamp($filters['publish_day_from']);
            $conds['publish_day_from'] = 'ca.publish_day >= ' . $publish_day_from;
        }
        if (empty($filters['publish_day_to'])) {
            $filters['publish_day_to'] = null;
        } else {
            $publish_day_to = get_time_stamp($filters['publish_day_to']);
            if (isset($publish_day_from)) {
                if ($publish_day_from >= $publish_day_to) {
                    $conds['publish_day_from'] = 'ca.publish_day >= ' . $publish_day_to;
                    $filters['publish_day_from'] = date('d/m/Y', $publish_day_to);
                }
            }
            $conds['publish_day_to'] = 'ca.publish_day <= ' . get_time_stamp($filters['publish_day_to'], true);
        }

        if (count($conds) == 0) {
            $query = 'SELECT COUNT(id) as count_result FROM cms_article ca LIMIT 0, 1';
        } else {
            $query = 'SELECT COUNT(id) as count_result FROM cms_article ca WHERE ' . implode(' AND ', $conds) . ' LIMIT 0, 1';
        }

        // Get Count Articles
        $rs = $this->cms_article_model->db->query($query);
        $count_results = $rs->row()->count_result;
        $rs->free_result();

        // Paginate
        if ($current_page <= 1) {
            $current_page = 1;
        }
        $start = ($current_page - 1) * $record_per_page;
        if ($start <= 0) {
            $start = 0;
        }
        $total_pages = ceil($count_results / $record_per_page);
        $delta = ceil(self::ARTICLE_PAGE_RANGE / 2);
        if ($current_page - $delta > $total_pages - self::ARTICLE_PAGE_RANGE) {
            $pag['lower'] = $total_pages - self::ARTICLE_PAGE_RANGE;
            $pag['upper'] = $total_pages;
        } else {
            if ($current_page - $delta < 0) {
                $delta = $current_page;
            }
            $offset = $current_page - $delta;
            $pag['lower'] = $offset + 1;
            $pag['upper'] = $offset + self::ARTICLE_PAGE_RANGE;
        }
        if ($pag['lower'] <= 1) {
            $pag['lower'] = 1;
        }
        if ($pag['upper'] >= $total_pages) {
            $pag['upper'] = $total_pages;
        }
        $pag['total'] = $total_pages;

        // Transfer Variables
        $data['module_title'] = $title;
        $data['return_url'] = $return_url;
        $data['record_per_page'] = $record_per_page;
        $data['rpps'] = $this->_rpps;
        foreach ($this->_bas as $action_label => $url) {
            if ($url == 'admin/cms/article/bulk_action/delete' && !$data['has_privilege_delete_article']) {
                unset($this->_bas[$action_label]);
                continue;
            }
            if ($url == 'admin/cms/article/bulk_action/editing' && !$data['has_privilege_edit_article']) {
                unset($this->_bas[$action_label]);
                continue;
            }
            if ($url == 'admin/cms/article/bulk_action/publish' && !$data['has_privilege_publish_article']) {
                unset($this->_bas[$action_label]);
                continue;
            }
            if ($url == 'admin/cms/article/bulk_action/unpublish' && !$data['has_privilege_unpublish_article']) {
                unset($this->_bas[$action_label]);
                continue;
            }
            $this->_bas[$action_label] = $url . '/return/' . $return_url;
        }
        $data['bas'] = $this->_bas;
        $data['categories'] = $this->cms_category_model->get_list();
        $data['users'] = $this->admin_model->get_list();
        $data['count_total'] = $count_results;
        $data['current_page'] = $current_page;
        $data['paginator'] = $pag;
        $data['filters'] = $filters;
        $data['collection'] = $this->cms_article_model->get_collection($start, $record_per_page, $conds, 'publish_day DESC, id DESC');
        $data['save_action'] = site_url('admin/cms/article/save', true);
        $data['admin_id'] = $this->admin_model->get_id();
        return $data;
    }

    public function filtered_list($alias) {
        try {
            $privileges = $this->check_has_privileges();
            global $active_article_function;
            $ajax_action = $this->input->getParam('ajax_action');
            $active_article_function = 'admin/cms/article/filtered_list/' . $alias;
            if ($alias != 'index') {
                switch ($alias) {
                    case 'publish':
                        if (!$privileges['has_privilege_publish_list']) {
                            $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền xem danh sách bài đã xuất bản');
                            redirect(site_url('admin/cms/article/restricted', true));
                            exit();
                        }
                        break;
                    case 'unpublish':
                        if (!$privileges['has_privilege_unpublish_list']) {
                            $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền xem danh sách bài đã gỡ bỏ');
                            redirect(site_url('admin/cms/article/restricted', true));
                            exit();
                        }
                        break;
                }
                $data_type = $this->cms_article_model->parse_alias($alias);
            } else {
                if (!$privileges['has_privilege_list']) {
                    $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền xem danh sách bài viết');
                    redirect(site_url('admin/cms/article/restricted', true));
                    exit();
                }
                $data_type['status'] = '';
                $data_type['label'] = ' trong hệ thống ';
            }
            $data = $this->_initListData($alias, $data_type['status'], $data_type['label'], $privileges);
            $data['form_action'] = site_url($active_article_function, true);
            if (empty($ajax_action)) {
                $this->setPageContent('admin/cms/article/list', $data);
                $this->renderLayout('layouts/fullcolumn');
            } else {
                $this->setPageContent('admin/cms/article/ajax/list', $data);
                $this->renderLayout('layouts/ajax');
            }
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    public function related_list($alias = 'publish') {
        try {
            $type = $this->input->getParam('type');
            if(!isset($type) || !$type){
                $type = 0;
            }

            $data = $this->check_has_privileges();
            $data = $this->_initListData($alias, 1, 'xuất bản', $data);
            $data['type'] = $type;

            if($type == 1){//check nếu là lấy tin liên quan đến bệnh thì mới lấy nhóm danh mục tránh gọi nhiều lần
                $data['category_relate'] = json_encode($this->cms_category_model->get_group_cat());
            }else{
                $data['category_relate'] = 0;
            }

            $this->setPageContent('admin/cms/article/ajax/related', $data);
            $this->renderLayout('layouts/ajax');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    public function preview_article() {
        $id = $this->input->getParam('id');
        $privileges = $this->check_has_privileges();
        if (!$privileges['has_privilege_view_article']) {
            echo 'Bạn không có quyền xem bài viết';
            exit();
        }
        if (empty($id)) {
            exit();
        }
        $data['article'] = $this->cms_article_model->load_by_id($id);
        $this->setPageContent('admin/cms/article/ajax/preview', $data);
        $this->renderLayout('layouts/ajax');
    }

    function save() {
        try {
            $privileges = $this->check_has_privileges();
            $this->load->helper('simple_html');
            $id = $this->input->post('id');
            $data = $this->input->post('data');
            $go_back = $this->input->post('go_back');
            $set_img_url = $this->input->post('set_img_url');
            $img_path = $this->input->post('img_path');
            $user_id = $this->admin_model->get_id();
            $updated_time = time();

            // Config Upload
            $config['allowed_types'] = 'gif|jpg|png|bmp|psd';
            $config['max_size'] = '500';
            $config['upload_path'] = './media/uploaded/' . date('Y', $updated_time) . '/' . date('m', $updated_time) . '/' . date('d', $updated_time) . '/';
            if (!file_exists($config['upload_path'])) {
                mkdir($config['upload_path'], 0777, true);
            }

            // Add new Article
            if (empty($id)) {
                // Has New And Editing Privileges
                if (!$privileges['has_privilege_new_article']) {
                    redirect(site_url('admin/cms/article/restricted', true));
                    exit();
                }
                $data['user_id'] = $user_id;
                $data['last_editor_id'] = $user_id;
                $data['created_at'] = $updated_time;
                $data['updated_at'] = $updated_time;
                if (isset($_FILES['data_image']) && $_FILES['data_image']['size'] > 0) {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    } else {
                        $this->upload->initialize($config);
                        $this->upload->do_upload('data_image');
                        // Render Image Path
                        $data_upload = $this->upload->data();
                        $image_path = $config['upload_path'] . $data_upload['file_name'];
                        if (strlen($data_upload['file_name']) > 0) {
                            $data['image'] = $image_path;
                        }
                    }
                } else {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    }
                }
                if (empty($data['image'])) {
                    $html = str_get_html($data['content']);
                    $images = $html->find('img');
                    if (count($images) > 0) {
                        foreach ($images as $image) {
                            if (!strstr($image->src, base_url())) {
                                $data['image'] = $image->src;
                                break;
                            }
                        }
                        $data['content'] = $html;
                    }
                }
                $id = $this->cms_article_model->add_article($data);
                $this->st_registry->register('admin/cms/article/success', 'Thêm bài viết mới thành công');
            } else {
                // Has Edit And Editing Privileges
                if (!$privileges['has_privilege_edit_article'] && !$privileges['has_privilege_editing_article']) {
                    redirect(site_url('admin/cms/article/restricted', true));
                    exit();
                }
                // Update Article
                $data['updated_at'] = $updated_time;
                $data['last_editor_id'] = $user_id;
                $article = $this->cms_article_model->load_by_id($id);
                if (!empty($article->upload_path)) {
                    $config['upload_path'] = $article->upload_path;
                }

                if (isset($_FILES['data_image']) && $_FILES['data_image']['size'] > 0) {
                    @unlink($article->image);
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    } else {
                        $this->upload->initialize($config);
                        $this->upload->do_upload('data_image');
                        // Render Image Path
                        $data_upload = $this->upload->data();
                        $image_path = $config['upload_path'] . $data_upload['file_name'];
                        if (strlen($data_upload['file_name']) > 0) {
                            $data['image'] = $image_path;
                        }
                    }
                } else {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    }
                }
                if (!isset($data['image'])) {
                    $data['image'] = $article->image;
                }
                if (empty($data['image'])) {
                    $html = str_get_html($data['content']);
                    $images = $html->find('img');
                    if (count($images) > 0) {
                        foreach ($images as $image) {
                            if (!strstr($image->src, base_url())) {
                                $data['image'] = $image->src;
                                break;
                            }
                        }
                        $data['content'] = $html;
                    }
                }
                $this->cms_article_model->update_article($id, $data);
                $this->st_registry->register('admin/cms/article/success', 'Lưu thông tin bài viết ['.$data['title'].'] thành công');
            }            
        } catch (Exception $ex) {
            $this->st_registry->register('admin/cms/article/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
        if (empty($go_back)) {
            redirect(site_url('admin/cms/article/edit/id/'.$id, true));
        } else {
            redirect(site_url('admin/cms/article/index', true));
        }
    }

    public function edit() {
        try {
            $is_admin = $this->admin_model->is_admin();
            $actions = $this->cms_article_model->get_all_status();
            $data = $this->check_has_privileges();
            global $active_article_function;
            $active_article_function = 'admin/cms/article/edit';
            $redirect_url = $this->_get_return_url($this->input->getParam('return'));
            $id = $this->input->getParam('id');
            if ($id) {
                $data['article'] = $this->cms_article_model->load_by_id($id);
                if (!$data['article']) {
                    $this->st_registry->register('Không tìm thấy bài viết theo yêu cầu của bạn!');
                    redirect(site_url('admin/cms/article/index', true));
                    return;
                }
            } else {
                if (!$data['has_privilege_new_article']) {
                    $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền tạo mới bài');
                    redirect(site_url('admin/cms/article/restricted', true));
                    exit();
                }
                $data['article'] = new stdClass();
            }
            if (!isset($data['article']->category_ids)) {
                $data['article']->category_ids = array();
            }
            $data['form_related_action'] = site_url('admin/cms/article/filtered_list/publish', true);
            if (!$is_admin) {
                if (!empty($cat_ids)) {
                    $data['categories'] = $this->cms_category_model->get_by_ids($cat_ids);
                }
            } else {
                $data['categories'] = $this->cms_category_model->get_list();
            }
            $data['actions'] = $actions;
            $data['users'] = $this->admin_model->get_list();
            $data['indexes'] = $this->cms_article_model->get_indexes();
            $data['return_url'] = $redirect_url;
            $this->setPageContent('admin/cms/article/edit', $data);
            $this->renderLayout('layouts/fullcolumn');
        } catch (Exception $ex) {
            $this->st_registry->register('admin/cms/article/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
    }

    private function is_ajax_request() {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            return true;
        }
        $ajax_action = $this->input->getParam('ajax_action');
        if (!empty($ajax_action)) {
            return true;
        }
        return false;
    }

    public function delete() {

        $return_url = $this->input->getParam('return');
        $ajax_action = $this->is_ajax_request();
        $id = $this->input->getParam('id');

        if (empty($id)) {
            $this->st_registry->register('admin/cms/article/error', 'Không xác định được bài viết cần xóa (ID)?');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
            exit();
        }

        $is_admin = $this->admin_model->is_admin();
        $admin_id = $this->admin_model->get_id();
        $privileges = $this->check_has_privileges();
        $article = $this->cms_article_model->load_by_id($id);

        if (empty($article)) {
            $this->st_registry->register('admin/cms/article/error', 'Không xác định được bài viết cần xóa (ID)?');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
            exit();
        }

        if (!$is_admin) {
            if ($admin_id != $article->user_id) {
                if (!$privileges['has_privilege_delete_article'] && !$privileges['has_privilege_editing_article']) {
                    $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền xóa bài viết');
                    if (empty($return_url)) {
                        if (!empty($ajax_action)) {
                            redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                        } else {
                            redirect(site_url('admin/cms/article/index', true));
                        }
                    } else {
                        if (!empty($ajax_action)) {
                            redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                        } else {
                            redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                        }
                    }
                }
            } else {
                if (!$privileges['has_privilege_editing_article'] && !$privileges['has_privilege_approved_article']) {
                    $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền xóa bài viết của đồng nghiệp');
                    if (empty($return_url)) {
                        if (!empty($ajax_action)) {
                            redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                        } else {
                            redirect(site_url('admin/cms/article/index', true));
                        }
                    } else {
                        if (!empty($ajax_action)) {
                            redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                        } else {
                            redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                        }
                    }
                    exit();
                }
            }
        }

        $this->cms_article_model->delete_article($id);
        $this->st_registry->register('admin/cms/article/success', 'Xóa bài viết thành công');
        if (empty($return_url)) {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/index/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/index', true));
            }
        } else {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
            }
        }
    }

    public function publish_article() {
        $return_url = $this->input->getParam('return');
        $ajax_action = $this->is_ajax_request();
        $id = $this->input->getParam('id');
        $privileges = $this->check_has_privileges();
        if (!$privileges['has_privilege_publish_article']) {
            $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền xuất bản bài viết');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
        }
        if (empty($id)) {
            $this->st_registry->register('admin/cms/article/error', 'Không xác định được bài viết cần xuất bản (ID)?');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
            exit();
        }
        $this->cms_article_model->update_status($id, 1);
        $this->st_registry->register('admin/cms/article/success', 'Xuất bản bài viết thành công');
        if (empty($return_url)) {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/index/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/index', true));
            }
        } else {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
            }
        }
    }

    public function unpublish_article() {
        $return_url = $this->input->getParam('return');
        $ajax_action = $this->is_ajax_request();
        $id = $this->input->getParam('id');
        $privileges = $this->check_has_privileges();
        if (!$privileges['has_privilege_unpublish_article']) {
            $this->st_registry->register('admin/cms/article/error', 'Bạn không có quyền gỡ bỏ bài viết');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
        }
        if (empty($id)) {
            $this->st_registry->register('admin/cms/article/error', 'Không xác định được bài viết cần gỡ bỏ (ID)?');
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
            exit();
        }
        $this->cms_article_model->update_status($id, 2);
        $this->st_registry->register('admin/cms/article/success', 'Gỡ bỏ bài viết thành công');
        if (empty($return_url)) {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/index/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/index', true));
            }
        } else {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
            }
        }
    }

    public function bulk_action($alias) {
        $return_url = $this->input->getParam('return');
        $ajax_action = $this->input->getParam('ajax_action');
        $data_type = $this->cms_article_model->parse_alias($alias);
        $ids = $this->input->getParam('selected');
        if (!is_array($ids) && empty($ids)) {
            $this->st_registry->register('admin/cms/article/error', 'Hãy chọn ít nhất một bài viết để ' . $data_type['label']);
            if (empty($return_url)) {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/index/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/index', true));
                }
            } else {
                if (!empty($ajax_action)) {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
                } else {
                    redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
                }
            }
            return;
        }
        $count = count($ids);
        foreach ($ids as $id) {
            $this->cms_article_model->update_status($id, $data_type['status']);
        }
        $this->st_registry->register('admin/cms/article/success', 'Thiết lập trạng thái ' . $data_type['label'] . ' (' . $count . ') bài viết thành công');
        if (empty($return_url)) {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/index/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/index', true));
            }
        } else {
            if (!empty($ajax_action)) {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url . '/ajax_action/true', true));
            } else {
                redirect(site_url('admin/cms/article/filtered_list/' . $return_url, true));
            }
        }
    }

    private function _get_return_url($url) {
        if (!empty($url)) {
            $return_url = site_url('admin/cms/article/filtered_list/' . $url, true);
        } else {
            if (isset($_SERVER['HTTP_REFERER'])) {
                $return_url = $_SERVER['HTTP_REFERER'];
            } else {
                $return_url = null;
            }
        }
        return $return_url;
    }

    public function ajax_update_hot_article() {
        $id = intval(trim($this->input->post('id')));
        $hot_article = intval(trim($this->input->post('hot_article')));
        $privileges = $this->check_has_privileges();
        if (!$privileges['has_privilege_set_hot_article']) {
            echo 'Bạn không có quyền thiết lập bài tiêu điểm';
            exit();
        }
        if (empty($id)) {
            echo 'error';
            exit();
        }
        $this->cms_article_model->db->query('UPDATE cms_article SET hot_article = ' . $hot_article . ' WHERE id = ' . $id);
        echo 'success';
    }

    public function ajax_update_top_home() {
        $id = intval(trim($this->input->post('id')));
        $top_home = intval(trim($this->input->post('top_home')));
        $privileges = $this->check_has_privileges();
        if (!$privileges['has_privilege_set_top_home']) {
            echo 'Bạn không có quyền thiết lập bài đầu trang chủ';
            exit();
        }
        if (empty($id)) {
            echo 'error';
            exit();
        }
        $this->cms_article_model->db->query('UPDATE cms_article SET top_home = ' . $top_home . ' WHERE id = ' . $id);
        echo 'success';
    }

    public function ajax_update_top_category() {
        $id = intval(trim($this->input->post('id')));
        $top_category = intval(trim($this->input->post('top_category')));
        $privileges = $this->check_has_privileges();
        if (!$privileges['has_privilege_set_top_category']) {
            echo 'Bạn không có quyền thiết lập bài đầu danh mục';
            exit();
        }
        if (empty($id)) {
            echo 'error';
            exit();
        }
        $this->cms_article_model->db->query('UPDATE cms_article SET top_category = ' . $top_category . ' WHERE id = ' . $id);
        echo 'success';
    }

    private function show_restricted_message($message) {
        echo '<div class="message error_message mt_10">'.$message.', <a href="" style="text-decoration: none; color: yellow">nạp lại trang</a></div>';
        return $this;
    }
}